import React, { useState, useEffect, useRef, useCallback } from "react";
import styled from "@emotion/styled";
import {
  Button,
  Table,
  Space,
  Avatar,
  Modal,
  Form,
  Input,
  Select,
  Tabs,
  Popconfirm,
  message,
} from "antd";
import BHeader from "components/bHeader/index";
import { padding, borderRadius } from "config/page";
import { useDebounce, getCurrent } from "utils/help";
import { ROLE } from "config";
import * as api from "api";
import { useAuth } from "context/auth-context";
const { Option } = Select;
const { TabPane } = Tabs;
export default function Member() {
  const { user } = useAuth();
  const form = useRef(null);
  const [isModalVisible, setIsModalVisible] = useState(false);
  // 是否编辑 当前item
  const [opt, setOpt] = useState("add");
  const [current, setCurrent] = useState();
  // 成员管理筛选
  const [filter, setFilter] = useState({
    current: 1,
    pageSize: 10,
    key: "",
  });

  // 成员管理列表
  const [memberInfo, setMemberInfo] = useState({
    total: 1,
    list: [],
  });

  // 防抖
  const newFilter = useDebounce(filter, 500);
  const checkUserOpt = useCallback(() => {
    let result = false;
    if (user?.roleId === 1) {
      result = true;
    }
    return result;
  }, [user]);

  // 接口请求
  useEffect(() => {
    getList(newFilter);
  }, [newFilter]);

  const edit = (item: any) => {
    setCurrent(item);
    setIsModalVisible(true);
    setOpt("edit");
  };

  let columns = [
    {
      title: "用户名",
      key: "userName",
      render: (item: any) => {
        return (
          <Space>
            <Avatar size={20}>{item.userName.substring(0, 1)}</Avatar>
            {item.userName}
          </Space>
        );
      },
    },
    {
      title: "账号名",
      key: "userLoginName",
      dataIndex: "userLoginName"
    },
    {
      title: "角色",
      render: (item: any) => {
        let arr: string[] = [];
        ROLE.forEach((role) => {
          if (role.key === item.role) {
            arr.push(role.value);
          }
        });
        return arr.map((r) => {
          return <span key={r}>{r}</span>;
        });
      },
    },
    {
      title: "邮箱",
      dataIndex: "email",
      key: "email",
    },
  ];

  if (user?.roleId === 1) {
    columns.push({
      title: "操作",
      key: "opt",
      render: (item: any) => {
        return (
          <div className="flex">
            <Button
              type="link"
              style={{ padding: 0 }}
              onClick={() => edit(item)}
            >
              编辑
            </Button>
            <Popconfirm
              title="是否删除该用户？"
              okText="确定"
              cancelText="取消"
              onConfirm={() => delUser(item)}
            >
              <Button type="link">删除</Button>
            </Popconfirm>
          </div>
        );
      },
    });
  }

  // 成员列表
  const getList = (params: {
    current: number;
    pageSize: number;
    key: string;
  }) => {
    api.getMemberList(params).then((res: any) => {
      setMemberInfo({
        list: res.list,
        total: res.totalCount,
      });
    });
  };

  // 完成
  const onFinish = (val: any) => {
    if (opt === "edit") {
      api
        .updateUserInfo(
          {
            userId: (current as any).userId,
          },
          {
            ...val,
            roleIdList: [val.roleIdList],
          }
        )
        .then(() => {
          message.success("修改成功!");
          setIsModalVisible(false);
          getList(filter);
        });
    } else {
      api
        .createUser({
          ...val,
          roleIdList: [val.roleIdList],
        })
        .then(() => {
          message.success("添加成员成功!");
          setIsModalVisible(false);
          getList(filter);
        });
    }
  };

  // 删除用户 （权限管理才有）
  const delUser = (val: any) => {
    api
      .batchDelet({
        user_id: val.userId,
      })
      .then(() => {
        message.success("删除成员成功!");
        if (getCurrent(memberInfo.total - 1, newFilter) === newFilter.current) {
          getList(newFilter);
        } else {
          setFilter({
            ...newFilter,
            current: getCurrent(memberInfo.total - 1, newFilter),
          });
        }
      });
  };

  const layout = {
    labelCol: { span: 24 },
    wrapperCol: { span: 24 },
  };
  return (
    <div>
      <BHeader
        title="成员管理"
        onSearchChange={(e: any) => {
          setFilter({
            ...filter,
            key: e.target.value,
          });
        }}
        btn={
          checkUserOpt() ? (
            <Button
              type="primary"
              shape="round"
              onClick={() => {
                setOpt("add");
                setIsModalVisible(true);
              }}
            >
              添加成员
            </Button>
          ) : (
            <span></span>
          )
        }
        placeholder="搜索成员"
      />
      <div style={{ padding: padding }}>
        {/* @ts-ignore */}
        <Wrapper borderRadius={borderRadius} padding={padding}>
          <div style={{ padding: 16 }}>
            <Tabs defaultActiveKey="1">
              <TabPane tab="成员列表" key="1">
                <Table
                  dataSource={memberInfo.list}
                  columns={columns}
                  rowKey="userId"
                  locale={{ emptyText: "暂无数据" }}
                  pagination={{
                    current: filter.current,
                    pageSize: filter.pageSize,
                    showSizeChanger: false,
                    total: memberInfo.total,
                    hideOnSinglePage: true,
                    onChange: (page) =>
                      setFilter({
                        ...filter,
                        current: page,
                      }),
                  }}
                />
              </TabPane>
            </Tabs>
          </div>
        </Wrapper>
      </div>
      <Modal
        title={opt === "edit" ? "编辑" : "邀请成员"}
        visible={isModalVisible}
        // @ts-ignore
        onOk={() => form.current.submit()}
        onCancel={() => setIsModalVisible(false)}
        destroyOnClose={true}
        cancelText="取消"
        okText="确定"
      >
        <Form
          {...layout}
          name="basic"
          initialValues={
            opt === "edit"
              ? {
                  ...(current as any),
                  roleId: (current as any).role
                }
              : {}
          }
          onFinish={onFinish}
          ref={form}
        >
          <Form.Item
            label="账户名"
            name="loginName"
            rules={[
              { required: true, message: "请输入账号名!" },
              { min: 3, message: "账户名必须在3-16个字符之间" },
            ]}
          >
            <Input
              disabled={opt === "edit"}
              maxLength={16}
              autoComplete="off"
            />
          </Form.Item>
          <Form.Item
            label="昵称"
            name="userName"
            rules={[
              { required: true, message: "请输入昵称!" },
              { min: 2, message: "昵称必须在2-16个字符之间" },
            ]}
          >
            <Input maxLength={16} autoComplete="off" />
          </Form.Item>

          {opt === "edit" ? null : (
            <Form.Item
              label="密码"
              name="password"
              rules={[{ required: true, message: "请输入账号密码!" }]}
            >
              <Input.Password />
            </Form.Item>
          )}

          <Form.Item
            label="邮箱地址"
            name="email"
            rules={[
              { required: true, message: "请输入邮箱地址!" },
              {
                type: "email",
                message: "请输入正确的邮箱地址",
              },
            ]}
          >
            <Input autoComplete="off" />
          </Form.Item>
          <Form.Item
            label="角色设置"
            name="roleId"
            rules={[{ required: true, message: "请选择角色!" }]}
          >
            <Select>
              {ROLE.map((item) => {
                // userRoot 超级管理员
                if (user?.roleId && item.key > user?.roleId) {
                  return (
                    <Option key={item.key} value={item.key}>
                      {item.value}
                    </Option>
                  );
                } else {
                  return null
                }
              })}
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}

const Wrapper = styled.div`
  background-color: #fff;
  box-sizing: border-box;
  min-height: ${(props: any) => `calc(100vh - ${props.padding * 2 + 165}px)`};
  border-radius: ${(props: any) => props.borderRadius + "px"};
  height: auto;
`;
